package com.sentiment.db;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.sentiment.obj.CrawlingPage;

/**
 * Mongodb detection Collection1 数据库CRUD类
 * 
 * @author wjk
 *
 */
public class CrawlingPageDB {
	private MongoClient mongoClient;
	private MongoDatabase mongodb;
	private MongoCollection<Document> mongoCollection;

	public CrawlingPageDB() {

		mongoClient = new MongoClient();

		mongodb = mongoClient.getDatabase("detection");

		mongoCollection = mongodb.getCollection("cpCollection");
	}

	public void DBClose() {
		mongoClient.close();
	}

	/**
	 * @param data
	 *            待存入数据库的数据结构
	 */
	public void insertData(CrawlingPage data) {

		// 创建一个document并插入
		Document doc = new Document("id", data.getId())
//				.append("html", data.getHtml())
				.append("url", data.getUrl())
				.append("title", data.getTitle())
				.append("crawlingTime", data.getCrawlingTime())
//				.append("encode", data.getEncode())
				.append("bySrc", data.getBySrc());

		mongoCollection.insertOne(doc);
	}
	public static final Logger log = LoggerFactory.getLogger(CrawlingPage.class);
	public CrawlingPage findDataByKeyAndVal(String key, String val) {
		
		Document mydoc = mongoCollection.find(Filters.eq(key, val)).first();
		if (mydoc == null)
			return null;
		return new CrawlingPage(mydoc);
	}

	public CrawlingPage findDataByDoubleKeyAndVal(String key1,String val1,String key2,String val2){
		Document doc = mongoCollection.find(new Document(key1,val1).append(key2, val2)).first();
		if(doc == null)
			return null;
		return new CrawlingPage(doc);
		
		
	}
	public List<CrawlingPage> findAllDataByKeyAndVal(String key, String val) {
		final List<CrawlingPage> li = new ArrayList<CrawlingPage>();
		FindIterable<Document> iter = mongoCollection.find(Filters.eq(key, val));
		iter.forEach(new Block<Document>() {

			@Override
			public void apply(final Document doc) {
				// TODO Auto-generated method stub
				CrawlingPage cp = new CrawlingPage(doc);
				li.add(cp);
			}

		});
		return li;
	}

	public void cleanAll() {
		// 清理掉collection中原有的数据
		mongoCollection.drop();
	}
}
